#include <iostream>
#include <time.h>
#include <unistd.h>
#include <assert.h>
#include "protocal.hpp"
#include "Sock.hpp"

const char opers[5] = {'+', '-', '*', '/', '%'};
const int size = 4096;

int main(int argc, char *argv[])
{
	std::string ip = argv[1];
	uint16_t port = std::stoi(argv[2]);
	Sock sock;
	sock.Socket();
	sock.Connect(ip, port);
	// lg(Info,"connect success");
	srand(time(nullptr) ^ getpid());
	int cnt = 1;
	while (true)
	{
		std::cout << "========这是第" << cnt << "次测试==============" << std::endl;
		int x = rand() % 10000;
		int y = rand() % 10000;
		char op = opers[rand() % 5];
		Request rq(x, y, op);
		rq.DebugPrint();
		std::string info;
		rq.Serialize(&info); // 序列化
		printf("这是最新发送的请求:");
		std::cout << info << std::endl;
		Encode(info); // 添加报文
		// std::cout << info.c_str() << std::endl;
		write(sock.Fd(), info.c_str(), info.size());
		// write(sock.Fd(), info.c_str(), info.size());
		// write(sock.Fd(), info.c_str(), info.size());

		std::string msg;
		// while (1)
		// {
		char buffer[size];
		int n = read(sock.Fd(), buffer, sizeof(buffer));
		if (n == 0)
			break;
		else if (n < 0)
			break;
		else
		{
			buffer[n] = 0;
			msg += buffer;
			while (true)
			{
				std::string res;
				bool r = Decode(msg, &res);
				if (!r)
					break;
				// std::cout << cnt << std::endl;
				std::cout << res << std::endl;
				Response rsp;
				rsp.Deserialize(res);
				rsp.DebugPrint();
			}
			// sleep(1);
		}
		std::cout << "=========================================" << std::endl;
		cnt++;
		sleep(1);
		// }
	}
	return 0;
}